<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\facade\Filesystem;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
/**
 * 产品报价单
 *
 * @icon fa fa-circle-o
 */
class Quotation extends Backend
{

    /**
     * Quotation模型对象
     * @var \app\admin\model\Quotation
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Quotation;

    }

    /**
     * 导出Excel模板
     */
    public function export_template()
    {
        $recordData = [];
        if (isset($_SERVER['HTTP_X_RECORD_DATA'])) {
            $recordData = json_decode($_SERVER['HTTP_X_RECORD_DATA'], true);
        }

        $templatePath = ROOT_PATH . 'public' . DS . 'template' . DS . 'excel' . DS . 'quotation.xlsx';

        if (!file_exists($templatePath)) {
            return $this->error('Excel模板文件不存在');
        }

        // 加载模板
        $spreadsheet = IOFactory::load($templatePath);
        $sheet = $spreadsheet->getActiveSheet();

        // 填充数据
        $this->fillTemplateData($sheet, $recordData);

        $filename = '报价单_' . date('YmdHis') . '.xlsx';

        // 输出到浏览器
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;
    }

    /**
     * 填充模板数据
     */
    private function fillTemplateData($sheet, $recordData)
    {
        // 根据您的模板结构自定义填充逻辑
        if (!empty($recordData) && isset($recordData['product_id'])) {
            $quotation = $this->model->get($recordData['id'] );
            $product = $quotation->product;
            $sheet->setCellValue('A13', $product->number);
            $sheet->setCellValue('C13', $product->specifications);
            $sheet->setCellValue('F13', $quotation->price);
            $sheet->setCellValue('F6', date('Y/m/d'));
        }
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
